import json

import joblib
from flask import Flask, render_template, request

from dbutils import DbHelper

app=Flask(__name__)
helper=DbHelper()
@app.route("/toFindBook")
def index():
    rs=helper.query("select * from books where id<5")
    last=json.dumps(rs,ensure_ascii=False)
    # last={"rs":rs}
    return last
@app.route("/toFindTop")
def findtop5():
    id = request.args.get("id")
    id = int(id)
    rs = helper.query(f"select * from books where id={id}")
    top5 = run(id)
    last=[rs,top5]
    return json.dumps(last,ensure_ascii=False)
@app.route("/")
def index2():
    rs = helper.query("select * from books where id<100")
    return render_template("index.html",rs=rs)
@app.route("/todetail")
def todetail():
    id=request.args.get("id")
    id=int(id)
    rs = helper.query(f"select * from books where id={id}")
    top5=run(id)
    return render_template("detail.html", rs=rs,top5=top5)
def run(id):
    with open("recs.pkl","rb") as f:
        model=joblib.load(f)
    # 第一本书
    first=model[id-1]
    b=list(enumerate(first))
    b.sort(key=lambda x:x[1],reverse=True)
    # 醉相思的前5本书
    top5=b[1:6]
    print(top5)
    top5=tuple(map(lambda x:x[0]+1,top5))
    last=helper.query(f"select id,title,coverpic from books where id in {top5}")
    print(last)
    return last
if __name__ == '__main__':
    app.run(host="0.0.0.0",port=3000)